package com.bluefuture.modules.sys.security.filter;

import com.bluefuture.modules.app.service.impl.UserDetailsServiceImpl;
import com.bluefuture.modules.sys.security.user.SysUserDetails;
import com.bluefuture.modules.sys.entity.SysUserTokenEntity;
import com.bluefuture.modules.sys.service.SysUserDetailsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author Clown
 * @Date 2021-08-29 00:22
 */
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = getRequestToken(request);
        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = userDetailsService.queryByToken(token);
        if (tokenEntity != null) {
            if (tokenEntity.getExpireTime().isAfter(LocalDateTime.now())) {
                SysUserDetails userDetails = (SysUserDetails) userDetailsService.loadUserByUsername(tokenEntity.getUserId().toString());
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        chain.doFilter(request,response);
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }

        return token;
    }
}
